package com.lw.nio.channel.fileChannel;

import org.junit.Test;

import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

/**
 * @author LW
 * @2021/9/12 18:52
 */
//通道间的传输
public class FileChannelWrite {
    /**
     * 批量复制文件
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        File dir = new File("C:\\Users\\ASUS\\Desktop\\a");
        // 判断是否存在目录
        if(dir.exists()) {
            // 读取目录下的所有目录文件信息
            String[] files = dir.list();
            RandomAccessFile aFile = null;
            RandomAccessFile bFile = null;
            for (int i = 0; i < files.length; i++) {
                File file = new File(dir, files[i]);
                System.out.println(file.getName());//文件名字
                aFile = new RandomAccessFile(file, "rw");
                FileChannel fromChannel = aFile.getChannel();
                //设置复制地址文件名（换了路径就用上面的getName）
                bFile = new RandomAccessFile(dir + "\\c"+i+".txt", "rw");
                FileChannel toChannel = bFile.getChannel();
                long position = 0;
                long count = fromChannel.size();
                toChannel.transferFrom(fromChannel, position, count);
                System.out.println(file);
            }
            aFile.close();
            bFile.close();
            System.out.println("结束了");
            System.out.println("文件夹存在");
        }

    }
    /**
     * 复制文件内容
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        //创建两个FileChannel
        RandomAccessFile aFile = new RandomAccessFile("C:\\Users\\ASUS\\Desktop\\a\\a.txt", "rw");
        FileChannel fromChannel = aFile.getChannel();

        RandomAccessFile bFile = new RandomAccessFile("C:\\Users\\ASUS\\Desktop\\a\\b.txt", "rw");
        FileChannel toChannel = bFile.getChannel();

        //fromChannel 传输到 toChannel
        long position = 0;
        long count = fromChannel.size();
        toChannel.transferFrom(fromChannel, position, count);
        //fromChannel.transferTo(position, count, fromChannel)
        //两个方法的方向不同

        aFile.close();
        bFile.close();
        System.out.println("结束了");
    }
}
